// pages/complaint/complaint.js
// pages/euqip/equip.js
const {
  API,
  defaultPage,
  equipStatusEnum,
  CLINIC_MANAGER_CODE
} = require('../../utils/const.js');
const {
  formVaildate,
  checkCount
} = require('../../utils/formCheckUtil.js');
const {
  getRequest,
  postRequest
} = require('../../utils/request.js');
const re = require('../../utils/request.js');
const {
  EuipFormRoles
} = require('../../utils/rulse.js');
const {
  hasRole
} = require('../../utils/userUtil.js');
var app = getApp();

Page({
  data: {
    patients: [],
    selectedPatient: '',
    selectedPatientName: '',
    materialBaseInfos: [],
    selectedMaterialBaseInfo: '',
    selectedMaterialBaseInfoName: '',
    selectedDate: ''
  },

   /**
   * Lifecycle function--Called when page load
   */
  onLoad(options) {
    const that = this;
    // 发起请求，获取数据
    getRequest(API.getMaterialBaseInfoList).then(res => {
      that.setData({
        materialBaseInfos: res
      });
    });

    getRequest(API.getPatientList).then(res => {
      that.setData({
        patients: res
      });
    });
  },

  onPatientChange: function(e) {
    const index = e.detail.value; // 获取选中的索引
    const selectedPatient = this.data.patients[index]; // 根据索引获取选中的患者对象

    // 设置选中的患者对象和名字
    this.setData({
      selectedPatient: selectedPatient,
      selectedPatientName: selectedPatient.patientName
    });
  },

  onMaterialBaseInfoChange(e) {
    const index = e.detail.value;
    const selectedMaterialBaseInfo = this.data.materialBaseInfos[index];

    this.setData({
      selectedMaterialBaseInfo: selectedMaterialBaseInfo,
      selectedMaterialBaseInfoName: selectedMaterialBaseInfo.materialName
    });
  },

  onDateChange: function(e) {
    this.setData({
      selectedDate: e.detail.value // 更新选中的日期
    });
  },

  onSubmit() {
    if (this.data.selectedPatient && this.data.selectedMaterialBaseInfo) {
      // 这里可以添加实际提交的代码逻辑
      const user = wx.getStorageSync('userInfo');
      const doctorId = user.userId;
      const patientId = this.data.selectedPatient.patientId;
      const materialId = this.data.selectedMaterialBaseInfo.id;
      const materialName = this.data.selectedMaterialBaseInfo.materialName;
      const selectedDate = this.data.selectedDate;
      var formValue = {
        'materialId': materialId,
        'materialName': materialName,
        'doctorId': doctorId,
        'patientId': patientId,
        'sendTime': new Date().toISOString(),
        'nextDoctorTime': selectedDate
      };
      postRequest(API.sendMaterial, formValue).then(res => {
        if (res) {
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000,
            complete: function() {
              // 延时跳转，确保提示显示完毕
              setTimeout(() => {
                wx.switchTab({
                  url: '/pages/home/home'
                });
              }, 2000);  // 2秒钟后跳转
            }
          });
        }
      });
    }
  }
});